<?php
/**
 * Created by jinqiang on 2025/4/8 15:59.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Services\Banshi;


use App\Http\Models\Mysql\MaterielCategoryTable;
use App\Http\Models\Mysql\MaterielTable;
use App\Http\Models\Mysql\SsyMaterialImagesTable;
use App\Http\Models\Mysql\StyleBomColourConfigTable;
use App\Http\Models\Mysql\StyleBomSizeConfigTable;
use App\Http\Models\Mysql\StyleBomTable;
use App\Http\Models\Mysql\StyleTable;
use App\Http\Models\Mysql\UnitTable;
use App\Http\Repository\CommonRepository;

class MaterielService
{
    public function search($param)
    {
        $conn = (new MaterielTable())->where('state', 0);
        if($param['materiel_category_id'] ?? []){//物料分类
            $materielCategoryId = end($param['materiel_category_id']);
            $conn = $conn->where('materiel_category_id', (Int)$materielCategoryId);
        }
        if($param['name'] ?? ""){//物料名称
            $conn = $conn->where('name', "like", "%".$param['name']."%");
        }
        if($param['number'] ?? ""){//物料编码
            $numbers = explode(",", $param['number']);
            $conn = $conn->whereIn('number', $numbers);
        }
        if($param['supplier'] ?? ""){
            $conn = $conn->where('supplier', $param['supplier']);
        }
        $res = $conn->orderBy('creation_time', 'desc')->paginate((Int)$param['limit'])->toArray();
        //获取图片
        $ids = array_column($res['data'], 'id');
        $imageList = (new SsyMaterialImagesTable())->whereIn('material_id', $ids)->get(['material_id', 'images'])->toArray();
        $imageMap = array_column($imageList, 'images', 'material_id');
        //获取物料分类
        $materielCategoryIds = array_unique(array_column($res['data'], 'materiel_category_id'));
        $mategoryCategoryList = (new MaterielCategoryTable())->whereIn('id', $materielCategoryIds)->get()->toArray();
        $mategoryCategoryMap = array_column($mategoryCategoryList, null, 'id');
        //物料主类型
        $categoryType = CommonRepository::CATEGORY;
        //物料单位
        $materielUnitList = (new UnitTable())->whereIn('id', array_unique(array_column($res['data'], 'materiel_major_unit_id')))->get()->toArray();
        $materielUnitMap = array_column($materielUnitList, 'name', 'id');
        foreach ($res['data'] as &$item){
            $mategoryCategory = $mategoryCategoryMap[$item['materiel_category_id']] ?? [];
            $item['materiel_category_pid'] = $mategoryCategory['pid'] ?? 0;
            $item['materiel_category_type'] = $mategoryCategory['name'] ?? $item['materiel_category_id'];
            $item['materiel_major_category_id'] = $mategoryCategory['materiel_major_category_id'] ?? "";
            $item['materiel_major_category_name'] = $categoryType[$mategoryCategory['materiel_major_category_id']] ?? "";
            $item['materiel_major_unit_name'] = $materielUnitMap[$item['materiel_major_unit_id']] ?? $item['materiel_major_unit_id'];
            $item['img'] = $imageMap[$item['id']] ?? "";
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function searchStyleBom($param)
    {
        $isProduct = (Int)$param['get_style_bom'];
        $conn = (new StyleBomTable())->where('is_product', $isProduct);
        if($param['typeNo'] ?? ""){
            $styleObj = (new StyleTable())->where('number', $param['typeNo'])->first();
            if(!empty($styleObj)){
                $conn = $conn->where('style_id', $styleObj->id);
            }
        }
        if($param['name'] ?? ""){
            $conn = $conn->where('materiel', 'like', '%'.$param['name'].'%');
        }
        if($param['number'] ?? ""){
            $numbers = explode(",", $param['number']);
            $conn = $conn->whereIn('materiel_number', $numbers);
        }
        if($param['supplier'] ?? ""){
            $conn = $conn->where('supplier', $param['supplier']);
        }
        $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
        $styleIds = array_column($res['data'], 'style_id');
        //获取图片
        $materielIds = array_column($res['data'], 'materiel_id');
        $imageList = (new SsyMaterialImagesTable())->whereIn('material_id', $materielIds)->get(['material_id', 'images'])->toArray();
        $imageMap = array_column($imageList, 'images', 'material_id');
        //缩水率
        $styleBomSizeConfigList = (new StyleBomSizeConfigTable())->whereIn('style_id', $styleIds)->where('is_product', $isProduct)->get(['style_bom_id', 'sr'])->toArray();
        $styleBomSizeConfigMap = array_column($styleBomSizeConfigList, 'sr', 'style_bom_id');
        //物料颜色
        $styleBomColourConfigList = (new StyleBomColourConfigTable())->whereIn('style_id', $styleIds)->where('is_product', $isProduct)->get(['style_bom_id', 'content'])->toArray();
        $styleBomColourConfigMap = [];
        foreach ($styleBomColourConfigList as $item) {
            $colour = json_decode($item['content'], true);
            if($colour[0]['code'] ?? ""){
                $colour[0]['code_ch'] = CommonRepository::getColor($colour[0]['code']);
            }
            $styleBomColourConfigMap[$item['style_bom_id']][] = $colour;
        }
        //来源款号
        $styleList = (new StyleTable())->whereIn('id', $styleIds)->get(['id', 'number'])->toArray();
        $styleMap = array_column($styleList, 'number', 'id');
        $data = [];
        foreach ($res['data'] as $item) {
            $sr = $styleBomSizeConfigMap[$item['id']] ?? "";
            $srArr = empty($sr) ? [] : explode(":", $sr);
            $styleBomId = $item['id'];
            $item['id'] = $item['materiel_id'];
            $item['type_no'] = $styleMap[$item['style_id']] ?? "";
            $item['name'] = $item['materiel'];
            $item['number'] = $item['materiel_number'];
            $item['materiel_category_type'] = $item['materiel_minor_category'];
            $item['materiel_category_id'] = $item['materiel_minor_category_id'];
            $item['materiel_major_category_name'] = $item['materiel_major_category'];
            $item['materiel_major_unit_name'] = $item['materiel_major_unit'];
            $item['img'] = $imageMap[$item['materiel_id']] ?? "";
            $item['style_bom_size_config'] = ['material_sr_e' => $srArr[0] ?? 0, 'material_sr_w' => $srArr[1] ?? 0];
            $item['style_bom_colour_config'] = [];
            if($styleBomColourConfigMap[$styleBomId] ?? []){
                foreach ($styleBomColourConfigMap[$styleBomId] as $colour){
                    $item['style_bom_colour_config']["#_0"] = $colour;
                    $data[] = $item;
                }
            }else{
                $data[] = $item;
            }
        }
        return [
            'data' => $data,
            'total' => count($data)
        ];
    }

    public function getMaterielCategory()
    {
        $list = (new MaterielCategoryTable())->get(['id', 'pid', 'name', 'materiel_major_category_id as category_id', 'materiel_attribute_id as attribute_id'])->toArray();
        $root = [];
        $children = [];
        foreach ($list as $item){
            $obj = ['value' => $item['id'], 'label' => $item['name'], 'category_id' => $item['category_id'], 'attribute_id' => $item['attribute_id']];
            if($item['pid'] == 0){
                $root[] = $obj;
            }else{
                $children[$item['pid']][] = $obj;
            }
        }
        foreach ($root as &$item){
            if(isset($children[$item['value']])){
                $item['children'] = $children[$item['value']];
            }
        }
        unset($item);
        $data = [];
        foreach ($root as $item) {
            if(isset($data[$item['category_id']])){
                $data[$item['category_id']]['children'][] = $item;
            }else{
                $data[$item['category_id']] = [
                    'value' => $item['category_id'],
                    'label' => CommonRepository::CATEGORY[$item['category_id']],
                    'disabled' => true,
                    'children' => [
                        $item
                    ]
                ];
            }
        }
        return array_values($data);
    }

    public function del($id)
    {
        $exists = (new StyleBomTable())->where('materiel_id', $id)->exists();
        if($exists){
            return ['code' => -1, 'msg' => '删除失败：该物料档案已被依赖'];
        }
        return (new MaterielTable())->deleteData($id);
    }

    public function save($param)
    {
        $id = $param['id'] ?? "";
        $user = auth()->guard("api")->user()->toArray();
        $data = [
            'name' => $param['name'],
            'materiel_major_unit_id' => $param['materiel_major_unit_id'],
            'materiel_minor_unit_id' => $param['materiel_minor_unit_id'],
            'materiel_attribute_id' => $param['materiel_attribute_id'],
            'materiel_category_id' => $param['materiel_category_id'],
            'remark' => $param['remark'] ?? "",
            'supplier_id' => $param['supplier_id'] ?? 0,
            'supplier' => $param['supplier'] ?? "",
            'supplier_contact_name' => $param['supplier_contact_name'] ?? "",
            'supplier_phone' => $param['supplier_phone'] ?? "",
            'supplier_address' => $param['supplier_address'] ?? "",
            'price' => (Double)($param['price'] ?? 0),
            'state' => $param['state'] ?? 0,
            'creator_id' => $user['id'],
            'creator' => $user['name'],
            'creation_time' => date('Y-m-d H:i:s')
        ];
        $materielAttribute = [];
        foreach ($param['materiel_attribute'] as $key => $item){
            if(!empty($item['value'])){
                $materielAttribute[$key] = $item;
            }
        }
        $data['materiel_attribute'] = json_encode($materielAttribute, JSON_UNESCAPED_UNICODE);
        if(!empty($id)){
            unset($data['creator'], $data['creation_time'], $data['creator_id']);
            $resp = (new MaterielTable())->updateData($id, $data);
        }else{
            $majorMap = [1 => "A", 2 => "B", 3 => "C"];
            $numberPre = "M".$majorMap[$param['materiel_major_category_id']].substr(date('Ym'), 2, 4);
            $materielObj = (new MaterielTable())->where('number', 'like', $numberPre."%")->orderBy('id', 'desc')->first(['number']);
            $num = 1;
            if(!empty($materielObj)){
                $num = (Int)(substr($materielObj->number, 6)) + 1;
            }
            $num = str_pad($num,3,"0",STR_PAD_LEFT);
            $data['number'] = $numberPre.$num;
            $resp = (new MaterielTable())->createData($data);
            $id = $resp['id'];
        }
        //存储物料图片
        if($param['img'] ?? ""){
            $exist = (new SsyMaterialImagesTable())->where('material_id', $id)->first();
            if(!empty($exist)){
                (new SsyMaterialImagesTable())->updateData($exist->id, ['images' => $param['img']]);
            }else{
                (new SsyMaterialImagesTable())->createData([
                    'images' => $param['img'],
                    'material_id' => $id,
                    'createtime' => date('Y-m-d H:i:s')
                ]);
            }
        }
        return $resp;
    }
}
